﻿using Abp;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.ObjectMapping;
using AutoMapper.QueryableExtensions;
using FwProject.BrandInfo.Dto;
using FwProject.ShopApplication;
using FwProject.ShopApplication.Configuration;
using FwProject.ShoppingMall.BrandInfo;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using X.PagedList;

namespace FwProject.BrandInfo
{
    /// <summary>
    /// 品牌管理
    /// </summary>
    public class BrandInfoAppService : FwProjectAppServiceBase, IBrandInfoAppService
    {
        private readonly IRepository<Brand, Guid> _repositoryBrand;
        private readonly IHostingEnvironment _hostingEnvironment;

        private readonly IConfigurationRoot _appConfiguration;
        /// <summary>
        /// guid 主键
        /// </summary>
        public IGuidGenerator _guid { get; set; }
        /// <summary>
        /// 映射对象
        /// </summary>
        public IObjectMapper _map { get; set; }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repositoryBrand"></param>
        /// <param name="hostingEnvironment"></param>
        public BrandInfoAppService(IRepository<Brand, Guid> repositoryBrand, IHostingEnvironment hostingEnvironment)
        {
            _repositoryBrand = repositoryBrand;
            _hostingEnvironment = hostingEnvironment;
            _appConfiguration = _hostingEnvironment.GetAppConfiguration();
            _guid = SequentialGuidGenerator.Instance;
        }

        #region 后台管理
        /// <summary>
        /// 后台管理-获取品牌的数据（layui数据格式）
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="limit">条数</param>
        /// <param name="keyword">关键词</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<LayerDataBaseDto> GetBrandLayerDataAsync(int page, int limit, string keyword)
        {
            var query = _repositoryBrand.GetAll();

            if (!string.IsNullOrWhiteSpace(keyword))
                query = query.Where(o => o.BrandName.Contains(keyword));

            var pagelist = await query.OrderByDescending(o => o.CreationTime).ProjectTo<BrandDto>().ToPagedListAsync(page, limit);

            LayerDataBaseDto dto = new LayerDataBaseDto();
            dto.Data = pagelist;
            dto.Count = pagelist.TotalItemCount;
            return dto;
        }


        /// <summary>
        /// 后台管理-获取一个输入模型
        /// </summary>
        /// <param name="id">品牌主键</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<BrandInput> GetEnterDtoAsync(Guid id)
        {
            var entity = await _repositoryBrand.GetAsync(id);
            var dto = entity.MapTo<BrandInput>();
            dto.BrandLogo = entity.Piclogo;
            return dto;
        }

        /// <summary>
        /// 后台管理-创建
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<Guid> CreateAsync(BrandInput input)
        {
            var model = _map.Map<Brand>(input);
            model.Id = _guid.Create();
            string FileTempPath = _appConfiguration["FileServicePath:TempBrand"];
            string FileSavaPath = _appConfiguration["FileServicePath:SavaBrand:SavaFilePath"];
            var path = SaveFile(input.BrandLogo, FileTempPath, FileSavaPath, $"{DateTime.Now.ToString("yyyyMMdd")}/");
            model.Piclogo = _appConfiguration["FileServicePath:SavaBrand:Virtual"] + path;
            var id = await _repositoryBrand.InsertAndGetIdAsync(model);
            return id;
        }
        /// <summary>
        /// 后台管理-修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<Guid> ModifyAsync(Guid id, BrandInput input)
        {
            var model = await _repositoryBrand.GetAsync(id);
            var originallogo = "";
            model = _map.Map(input, model);

            if (!string.IsNullOrEmpty(input.BrandLogo))
            {
                if (!string.IsNullOrEmpty(model.Piclogo))
                {
                    var l = model.Piclogo.Split('/');
                    originallogo = l[l.Length - 1];
                }
                string FileTempPath = _appConfiguration["FileServicePath:TempBrand"];
                string FileSavaPath = _appConfiguration["FileServicePath:SavaBrand:SavaFilePath"];
                var path = SaveFile(input.BrandLogo, FileTempPath, FileSavaPath, $"{DateTime.Now.ToString("yyyyMMdd")}/", originallogo);
                model.Piclogo = _appConfiguration["FileServicePath:SavaBrand:Virtual"] + path;
            }

            var entity = await _repositoryBrand.UpdateAsync(model);
            return entity.Id;
        }

        /// <summary>
        /// 后台管理-删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task DeleteAsync(Guid id)
        {
            var entity = await _repositoryBrand.GetAsync(id);
            await _repositoryBrand.DeleteAsync(entity);
        }
        #endregion

        /// <summary>
        /// 获取一个品牌
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public BrandDto GetByIdAsync(Guid id) {
            var entity =  _repositoryBrand.Get(id);
            var dto = entity.MapTo<BrandDto>();
            return dto;
        }

    }
}
